import $ from 'jquery';
import request from './request';
import docMaker from './docMaker';
import { Toast } from 'vant';

const DOMAIN = 'https://www.biquzw.la/';

function URLAfterDeal(url) {
    if (/^https?:\/\//.test(url)) {
        return url
    } else {
        return DOMAIN + url
    }
}

class ReaderDriver {

    async search(keyword) {
        const result = [];
        try {
            const res = await request({
                url: DOMAIN + '/modules/article/search.php',
                data: {
                    searchkey: keyword
                }
            });
            let doc = docMaker();
            doc.body.innerHTML = res;
            let $$ = $(doc);
            doc = null;
            $$.find('.grid tbody > tr').each(function (i, elem) {
                const name = $(elem).find('td:eq(0)').text();
                const article = $(elem).find('td:eq(1)').text();
                const author = $(elem).find('.odd:eq(1)').text();
                const path = $(elem).find('td:eq(0)').find('a').attr('href');
                const status = $(elem).find('td:eq(-1)').text();
                if (name && author) {
                    result.push(
                        {
                            type: '.biquge',
                            name,
                            article,
                            author,
                            status,
                            path
                        }
                    );
                }
            });
            $$ = null;
        } catch (error) {
            Toast('数据异常，请稍后再试')
            console.warn(error);

        }
        return result;
    }

    // 获取书籍信息以及章节列表
    async getInfoAndChapter(pathStr) {
        const result = {
            type: '.biquge',
            name: '',
            kind: '',
            author: '',
            icon: '',
            desc: '',
            chapterList: []
        };
        try {
            const res = await request({
                url: URLAfterDeal(pathStr)
            });
            let doc = docMaker();
            doc.body.innerHTML = res;
            let $$ = $(doc);
            doc = null;

            // 数据采集
            result.name = $$.find('#info h1').text();
            result.author = $$.find('#info p:eq(0)').text().split(':')[1] || '佚名';
            result.kind = $$.find('#info p:eq(1)').text().split(':')[1] || '未知';
            result.icon = $$.find('#fmimg img').attr('src');
            result.desc = $$.find('#intro p:eq(0)').text();
            $$.find('#list dd').each(function (i, elem) {
                const name = $(elem).find('a').text();
                const path = $(elem).find('a').attr('href');
                result.chapterList.push(
                    {
                        name,
                        path: pathStr + path,
                    }
                );
            });
            $$ = null;
        } catch (error) {
            Toast('数据异常，请稍后再试')
            console.warn(error);
        }
        return result;
    }

    // 获取书籍章节列表
    async getChapter(pathStr) {
        const result = [];
        try {
            const res = await request({
                url: URLAfterDeal(pathStr)
            });
            let doc = docMaker();
            doc.body.innerHTML = res;
            let $$ = $(doc);
            doc = null;

            // 数据采集
            $$.find('#list dd').each(function (i, elem) {
                const name = $(elem).find('a').text();
                const path = $(elem).find('a').attr('href');
                result.push(
                    {
                        name,
                        path: pathStr + path,
                    }
                );
            });
            $$ = null;
        } catch (error) {
            Toast('数据异常，请稍后再试')
            console.warn(error);
        }
        return result;
    }

    // 获取章节内容
    async getContent(pathStr, rootPathStr, countLimit = 100) {
        const result = {
            title: '',
            content: '',
            totalCount: 0,
            pageNo: 0,
            totalPage: 0,
            list: [],
            prev: null,
            next: null
        };
        try {
            const res = await request({
                url: URLAfterDeal(pathStr)
            });
            const chapterList = await this.getChapter(rootPathStr);
            let doc = docMaker();
            doc.body.innerHTML = res;
            let $$ = $(doc);
            doc = null;
            let title = $$.find('.bookname h1').text();
            let findIndex = chapterList.findIndex(d => d.name == title);
            result.title = title;
            result.list = chapterList;
            result.totalCount = chapterList.length;
            result.pageNo = Math.floor(findIndex / countLimit);
            result.totalPage = Math.ceil(chapterList.length / countLimit) - 1;
            result.content = $$.find('#content').html() || '';
            result.prev = chapterList[findIndex - 1] || null;
            result.next = chapterList[findIndex + 1] || null;
            $$ = null;
        } catch (error) {
            Toast('数据异常，请稍后再试')
            console.warn(error);
        }
        return result;
    }

    // 获取书籍信息
    async getInfo(pathStr) {
        const result = {};
        try {
            const res = await request({
                url: URLAfterDeal(pathStr)
            });
            let doc = docMaker();
            doc.body.innerHTML = res;
            let $$ = $(doc);
            doc = null;
            result.icon = $$.find('#fmimg img').attr('src');
            result.desc = $$.find('#intro p:eq(0)').text();
            // result.name = $$.find('#info h1').text();
            // result.author = $$.find('#info p:eq(0)').text().split(':')[1] || '佚名';
            $$ = null;
        } catch (error) {
            Toast('数据异常，请稍后再试')
            console.warn(error);
        }
        return result;
    }

    // 获取推荐阅读
    async getRecommend() {
        const result = [];
        try {
            const res = await request({
                url: DOMAIN
            });
            let doc = docMaker();
            doc.body.innerHTML = res;
            let $$ = $(doc);
            doc = null;
            $$.find('#hotcontent .l .item').each((i, el) => {
                let imgTag = $(el).find('.image img');
                let aTag = $(el).find('.image a');
                let spanTag = $(el).find('dl dt span');
                let ddTag = $(el).find('dl dd');
                let icon = imgTag.attr('src')
                let name = imgTag.attr('alt')
                let desc = ddTag.text()
                let path = aTag.attr('href')
                let author = spanTag.text() || '佚名'
                result.push(
                    {
                        type: '.biquge',
                        icon,
                        name,
                        path,
                        desc,
                        author
                    }
                );
            })
            $$.find('.novelslist .content .top').each((i, el) => {
                let imgTag = $(el).find('.image img');
                let aTag = $(el).find('.image a');
                let dtTag = $(el).find('dl dt');
                let ddTag = $(el).find('dl dd');
                let icon = imgTag.attr('src')
                let name = imgTag.attr('alt')
                let desc = ddTag.text()
                let path = aTag.attr('href')
                let author = dtTag.text().split('：')[1] || '佚名'
                result.push(
                    {
                        type: '.biquge',
                        icon,
                        name,
                        path,
                        desc,
                        author
                    }
                );
            })
            $$ = null;
        } catch (error) {
            Toast('数据异常，请稍后再试')
            console.warn(error);
        }
        return result;
    }

    // 获取与排行榜
    async getRank(type, limit = 10, pageNo = 1) {
        const result = [];
        let pathStr = '';
        switch (type) {
            case 'week':
                pathStr = '/paihangbang_weekvisit/' + pageNo + '.html'
                break;
            case 'all':
                pathStr = '/paihangbang_allvisit/' + pageNo + '.html'
                break;
            case 'hot':
                pathStr = '/paihangbang_allvote/' + pageNo + '.html'
                break;
            default:
                return result;
        }
        try {
            const res = await request({
                url: DOMAIN + pathStr
            });
            let doc = docMaker();
            doc.body.innerHTML = res;
            let $$ = $(doc);
            doc = null;
            $$.find('#main li').each((i, el) => {
                let s2Atag = $(el).find('.s2 a');
                let s4tag = $(el).find('.s4');
                let name = s2Atag.text()
                let author = s4tag.text() || '佚名'
                let path = s2Atag.attr('href')

                result.push(
                    {
                        type: '.biquge',
                        path,
                        name,
                        author,
                        icon: '',
                        desc: ''
                    }
                );
            })
            result.splice(limit);
            $$ = null;
        } catch (error) {
            Toast('数据异常，请稍后再试')
            console.warn(error);
        }
        return result;
    }
}

export default new ReaderDriver();

